<?php
namespace app\controller;

use support\Request;
use support\Db;

class TransactionController
{
    /**
     * 验证用户是否有权限操作该账本
     */
    private function checkBookPermission($bookId, $userId)
    {
        return Db::table('account_book_users')
            ->where('book_id', $bookId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->exists();
    }

    /**
     * 创建流水记录
     */
    public function create(Request $request)
    {
        try {
            $data = [
                'book_id' => $request->post('book_id'),
                'category_id' => $request->post('category_id'),
                'user_id' => $request->uid,
                'type' => $request->post('type'), // 1支出 2收入
                'amount' => $request->post('amount'),
                'remark' => $request->post('remark', ''),
                'trans_date' => $request->post('trans_date', date('Y-m-d')),
                'created_at' => date('Y-m-d H:i:s')
            ];

            // 验证必填字段
            if (empty($data['book_id']) || empty($data['category_id']) || 
                empty($data['type']) || empty($data['amount'])) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($data['book_id'], $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 验证分类是否属于该账本
            $category = Db::table('categories')
                ->where('id', $data['category_id'])
                ->where('book_id', $data['book_id'])
                ->where('status', 1)
                ->first();

            if (!$category || $category->type != $data['type']) {
                return json([
                    'code' => 400,
                    'msg' => '分类不存在或类型不匹配'
                ]);
            }

            $id = Db::table('transactions')->insertGetId($data);

            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => ['id' => $id]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取流水列表
     */
    public function list(Request $request)
    {
        try {
            $bookId = $request->get('book_id');
            $type = $request->get('type'); // 可选，筛选收支类型
            $startDate = $request->get('start_date');
            $endDate = $request->get('end_date');
            $page = $request->get('page', 1);
            $pageSize = $request->get('page_size', 20);
            $userId = $request->get('user_id');
            $categoryId = $request->get('category_id');

            if (empty($bookId)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            $query = Db::table('transactions as t')
                ->join('categories as c', 't.category_id', '=', 'c.id')
                ->join('wa_users as u', 't.user_id', '=', 'u.id')
                ->where('t.book_id', $bookId)
                ->where('t.status', 1);

            if ($type) {
                $query->where('t.type', $type);
            }
            if ($startDate) {
                $query->where('t.trans_date', '>=', $startDate);
            }
            if ($endDate) {
                $query->where('t.trans_date', '<=', $endDate);
            }
            if ($categoryId) {
                $query->where('t.category_id', $categoryId);
            }
            if ($userId) {
                $query->where('t.user_id', $userId);
            }

            $total = $query->count();

            $list = $query->select([
                't.*',
                'c.name as category_name',
                'c.color as category_color',
                'u.nickname as user_nickname',
                'u.avatar as user_avatar'
            ])
                ->orderBy('t.trans_date', 'desc')
                ->orderBy('t.created_at', 'desc')
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 计算统计数据
            $stats = Db::table('transactions')
                ->where('book_id', $bookId)
                ->where('status', 1)
                ->when($startDate, function($query) use ($startDate) {
                    return $query->where('trans_date', '>=', $startDate);
                })
                ->when($endDate, function($query) use ($endDate) {
                    return $query->where('trans_date', '<=', $endDate);
                })
                ->when($categoryId, function($query) use ($categoryId) {
                    return $query->where('category_id', $categoryId);
                })
                ->when($userId, function($query) use ($userId) {
                    return $query->where('user_id', $userId);
                })
                ->selectRaw('
                    SUM(CASE WHEN type = 1 THEN amount ELSE 0 END) as total_expense,
                    SUM(CASE WHEN type = 2 THEN amount ELSE 0 END) as total_income
                ')
                ->first();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'stats' => [
                        'total_expense' => $stats->total_expense ?: 0,
                        'total_income' => $stats->total_income ?: 0,
                        'net_amount' => bcsub($stats->total_income ?: 0, ($stats->total_expense ?: 0), 2)
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 更新流水记录
     */
    public function update(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取原记录
            $transaction = Db::table('transactions')
                ->where('id', $id)
                ->where('status', 1)
                ->first();

            if (!$transaction) {
                return json([
                    'code' => 404,
                    'msg' => '记录不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($transaction->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            $data = [
                'category_id' => $request->post('category_id'),
                'amount' => $request->post('amount'),
                'remark' => $request->post('remark'),
                'trans_date' => $request->post('trans_date'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            // 过滤空值
            $data = array_filter($data, function($value) {
                return $value !== null;
            });

            if (isset($data['category_id'])) {
                // 验证分类是否属于该账本且类型匹配
                $category = Db::table('categories')
                    ->where('id', $data['category_id'])
                    ->where('book_id', $transaction->book_id)
                    ->where('status', 1)
                    ->where('type', $transaction->type)
                    ->first();

                if (!$category) {
                    return json([
                        'code' => 400,
                        'msg' => '分类不存在或类型不匹配'
                    ]);
                }
            }

            Db::table('transactions')
                ->where('id', $id)
                ->update($data);

            return json([
                'code' => 0,
                'msg' => '更新成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除流水记录
     */
    public function delete(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取原记录
            $transaction = Db::table('transactions')
                ->where('id', $id)
                ->where('status', 1)
                ->first();

            if (!$transaction) {
                return json([
                    'code' => 404,
                    'msg' => '记录不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($transaction->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            Db::table('transactions')
                ->where('id', $id)
                ->update([
                    'status' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取流水详情
     */
    public function detail(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取流水记录详情
            $transaction = Db::table('transactions as t')
                ->join('categories as c', 't.category_id', '=', 'c.id')
                ->join('wa_users as u', 't.user_id', '=', 'u.id')
                ->where('t.id', $id)
                ->where('t.status', 1)
                ->select([
                    't.*',
                    'c.name as category_name',
                    'c.color as category_color',
                    'u.nickname as user_nickname',
                    'u.avatar as user_avatar'
                ])
                ->first();

            if (!$transaction) {
                return json([
                    'code' => 404,
                    'msg' => '记录不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($transaction->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限查看'
                ]);
            }

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $transaction
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 